// 新增机构、编辑机构
import React from 'react';
import { observer, useLocalStore } from 'mobx-react-lite';
import { useLocation, useHistory } from 'react-router';
import { parse } from 'qs';
import { Card, Form, Row, Col, Input, Button, message } from 'antd';
import * as addApi from '~/apis/case/listApi';
import AjaxSelect from '~/components/AjaxSelect';
import { formatFileList } from '~/components/PictureUploader';
import { FileUploader } from '~/components/FileUploader';
import { genValidConfig } from './pageConfig';
import './index.local.sass';

const FormItem = Form.Item;

const formItemLayout = {
  wrapperCol: { span: 20 },
};

const cardConfig = {
  size: 'small' as const,
  bordered: false,
};


const AddOrEditInstitution = observer(() => {
  const location = useLocation();
  const history = useHistory();

  const querryParams = parse(location.search, { ignoreQueryPrefix: true });

  const state = useLocalStore(() => ({
    id: querryParams.id || '',
    loading: false,
  }));

  const [form] = Form.useForm();

  // 获取表单数据
  const getFormValus = () => form.validateFields().then((values: any) => {
    const params = {
      id: state.id,
      ...values,
      caseUrl: values.fileList.map((v: any) => v.response.data).toString(),
    };

    // delete params.logoList;
    // delete params.fileList;

    return params;
  });

  const onSubmit = () => {
    getFormValus().then((params) => {
      addApi.addCase(params).then(() => {
        message.success('success');
        history.push('/case/my');
      });
    }).catch(() => {
      message.error('validation error');
    });
  };

  const onSaveAndClose = () => {
    getFormValus().then((params) => {
      addApi.addCase(params).then(() => {
        message.success('success');

        history.push('/case/my');
      });
    }).catch(() => {
      message.error('validation error');
    });
  };

  // 表单填充
  const fillForm = (formData: any) => {
    const {
      id,
      caseName,
      countryId,
      industryId,
      caseUrl,
    } = formData;
    form.setFieldsValue({
      id,
      caseName,
      countryId,
      industryId,
      fileList: formatFileList(caseUrl ? caseUrl.split(',') : []),
    });
  };

  // initForm
  const initForm = (id: string) => {
    addApi.getCase(id).then((res) => {
      fillForm(res.data);
      // console.log(res);
    });
  };

  React.useEffect(() => {
    if (state.id) {
      initForm(state.id);
    }
  }, []);

  return (
    <div className="card-wrap">
      <Card
        className="card"
        {...cardConfig}
      >
        <Form form={form} layout="vertical" className="w-11/12">

          {/* line 5 */}
          <Row>
            <Col span={7}>
              <FormItem
                name="caseName"
                label="Case Name"
                rules={genValidConfig('Institution Website')}
              >
                <Input
                  className="w-full-fix"
                />
              </FormItem>
            </Col>
          </Row>

          {/* line 6 */}
          <Row>
            <Col span={8}>
              <FormItem
                name="countryId"
                label="Country/Region"
                rules={genValidConfig('Country/Region')}
                {...formItemLayout}
              >
                <AjaxSelect
                  placeholder="Please select"
                  type="countryList"
                />
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span={8}>
              <FormItem
                name="industryId"
                label="Industry"
                rules={genValidConfig('Industry')}
                {...formItemLayout}
              >
                <AjaxSelect
                  placeholder="Industry"
                  type="industryList"
                />
              </FormItem>
            </Col>
          </Row>

          {/* line 9 */}
          <Row>
            <Col span={12}>
              <FormItem
                name="fileList"
                label="Related Cases"
                rules={genValidConfig('Related Cases')}
              >
                <FileUploader
                  multiple
                  accept="
                    application/zip,
                    application/vnd.rar,
                    application/msword,
                    application/vnd.openxmlformats-officedocument.wordprocessingml.document,
                    application/pdf
                  "
                />
              </FormItem>
              <div className="text-xs cor-grey">Support ZIP RAR DOC DOCX PDF only</div>
            </Col>
          </Row>

        </Form>
      </Card>

      <div>
        <Button
          type="primary"
          className="mr-2"
          onClick={onSubmit}
        >
          Submit Certification
        </Button>

        <Button
          className="mr-2"
          onClick={onSaveAndClose}
        >
          Save and Close
        </Button>
      </div>
    </div>
  );
});

export default AddOrEditInstitution;
